package com.bookkeeping.cn;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bookkeeping.cn.LoginActivity;
import com.bookkeeping.cn.R;
import com.bookkeeping.cn.adapter.BookKeepAdapter;
import com.bookkeeping.cn.adapter.BookKeepItemClick;
import com.bookkeeping.cn.databinding.FragmentHomeBinding;
import com.bookkeeping.cn.model.BookKeepDto;
import com.bookkeeping.cn.util.OkHttpUtil;
import com.bookkeeping.cn.util.URLUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class CountActivity extends Fragment {

    private FragmentHomeBinding binding;
    private TextView dateTv;
    Integer year, month;
    DatePickerDialog dlg;

    ListView dataLv ;
    BookKeepAdapter bookKeepAdapter;

    TextView sumTv;

    TextView useSumTv;

    Button add_record_btn;
    List<BookKeepDto> list;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        dateTv = binding.dateTv;
        sumTv=binding.sumTv;
        useSumTv=binding.useSumTv;
        dataLv=binding.dataLv;
        add_record_btn=binding.addRecordBtn;
        list=new ArrayList<>();

        bookKeepAdapter=new BookKeepAdapter(getContext(), R.layout.book_keep_item,list);
        dataLv.setAdapter(bookKeepAdapter);

        bookKeepAdapter.setBookKeepItemClick(new BookKeepItemClick() {
            @Override
            public void itemClick(Integer type, Integer position) {

            }
        });

        dateTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dlg.show();
                // Set year spinner as first selection
                NumberPicker yearSpinner = dlg.getDatePicker().findViewById(
                        Resources.getSystem().getIdentifier("year", "id", "android"));
                if (yearSpinner != null) {
                    yearSpinner.requestFocus();
                }
            }
        });

        // Get current date
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;

        updateDateText();

        dlg = new DatePickerDialog(new ContextThemeWrapper(getActivity(),
                android.R.style.Theme_Holo_Light_Dialog_NoActionBar),
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int day) {
                        year = selectedYear;
                        month = selectedMonth + 1;
                        getList();
                        updateDateText();
                    }
                }, year, month - 1, 1) {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                // Hide day picker
                View dayPickerView = findViewById(getContext().getResources().getIdentifier("android:id/day", null, null));
                if (dayPickerView != null) {
                    dayPickerView.setVisibility(View.GONE);
                }


                LinearLayout mSpinners = findViewById(getContext().getResources().getIdentifier("android:id/pickers", null, null));
                if (mSpinners != null) {
                    NumberPicker mMonthSpinner = findViewById(getContext().getResources().getIdentifier("android:id/month", null, null));
                    NumberPicker mYearSpinner = findViewById(getContext().getResources().getIdentifier("android:id/year", null, null));

                    if (mMonthSpinner != null && mYearSpinner != null) {
                        mSpinners.removeAllViews();
                        mSpinners.addView(mYearSpinner);
                        mSpinners.addView(mMonthSpinner);

                        mMonthSpinner.setDisplayedValues(getMonthDisplayValues());
                    }
                }
            }
        };

        // Set title
        dlg.setTitle("选择日期");
        getList();
        return root;
    }

    private void updateDateText() {
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("选择日期:").append(year).append("年").append(month).append("月");
        dateTv.setText(stringBuffer);
    }

    private String[] getMonthDisplayValues() {
        String[] months = new String[12];
        for (int i = 0; i < 12; i++) {
            months[i] = String.valueOf(i + 1);
        }
        return months;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
    // 获取列表接口
    private  void getList(){
        String token=URLUtil.TOKEN;
        Request request = new Request.Builder()
                .url(URLUtil.GET_BOOK_KEEP_LIST+"?year="+year+"&month="+month)
                .get()
                .addHeader("Authorization",  URLUtil.TOKEN)
                .build();

        OkHttpUtil.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast("网络请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                JSONObject jsonObject = JSON.parseObject(str);

                if (jsonObject.getInteger("code") == 1) {
                    //获取成功解析数据
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            list.clear();
                            list.addAll(JSON.parseArray(jsonObject.getString("content"),BookKeepDto.class));
                            //统计总收入
                            sumTv.setText(list.stream().filter(x->x.getType().equals(1)).map(x->x.getPrice()).reduce(BigDecimal.ZERO,BigDecimal::add).toString()+"元");
                            //统计总消费
                            useSumTv.setText(list.stream().filter(x->x.getType().equals(0)).map(x->x.getPrice()).reduce(BigDecimal.ZERO,BigDecimal::add).toString()+"元");
                            bookKeepAdapter.notifyDataSetChanged();
                        }
                    });
                } else if (jsonObject.getInteger("code")==-9) {
                    logout();
                }
                showToast(jsonObject.getString("message"));
            }
        });
    }
    private void showToast(String message) {
        getActivity().runOnUiThread(() ->
                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show()
        );
    }
    private void logout() {
        SharedPreferences.Editor editor=getActivity().getSharedPreferences("token_file", Context.MODE_PRIVATE).edit();
        editor.remove("token");
        editor.apply();
        startActivity(new Intent(getContext(), LoginActivity.class));
        getActivity().finish();
    }

}